<template>
  <!-- 租户号 -->
  <q-input v-if="false" ref="tenInput" v-model="loginForm.tenantId" :loading="loading"
           :placeholder="`${$t('PleaseInput')} ${$t('TenantCode')}`" :readonly="loading"
           :rules="[ val => val && val.length > 0 || `${$t('PleaseInput')} ${$t('TenantCode')}`]" dense lazy-rules
           @keydown.enter="setKeyCode" @keyup.enter="login('Tenant')">
    <template v-slot:prepend>
      <q-icon name="group" />
    </template>
  </q-input>
  <!-- 用户名 -->
  <q-input ref="nameInput" v-model="loginForm.loginName" :loading="loading"
           :placeholder="`${$t('PleaseInput')} ${$t('AccountTip1')}`" :readonly="loading"
           :rules="[val => val && val.length > 0 || `${$t('PleaseInput')} ${$t('AccountTip1')}`]" dense lazy-rules
           @keydown.enter="setKeyCode" @keyup.enter="login('Input')">
    <template v-slot:prepend>
      <q-icon name="account_circle" />
    </template>
  </q-input>
  <!-- 密码 -->
  <q-input ref="pwdInput" v-model="loginForm.password" :loading="loading"
           :placeholder="`${$t('PleaseInput')} ${$t('Password')}`" :readonly="loading"
           :rules="[val => val && val.length > 0 || `${$t('PleaseInput')} ${$t('Password')}`]"
           :type="isPwd ? 'password' : 'text'" dense lazy-rules @keydown.enter="setKeyCode" @keyup.enter="login('PWD')">
    <template v-slot:prepend>
      <q-icon name="lock" />
    </template>
    <template v-if="!loading" v-slot:append>
      <q-icon :name="isPwd ? 'visibility_off' : 'visibility'" class="cursor-pointer" @click="togglePWD" />
    </template>
  </q-input>

  <div class="row text-grey-7 justify-between q-pb-md q-mt-none">
    <q-checkbox v-model="rememberMe">{{ $t('RememberMe') }}</q-checkbox>
    <q-btn :label="`${$t('ForgotPwd')}`" dense flat padding=".5rem" @click="modalVisible = true" />
  </div>

  <!-- 登录按钮 -->
  <q-btn :loading="loading" class="bg-login-btn text-subtitle1 text-weight-bold full-width" flat rounded
         text-color="white" @click="login">
    {{ `${$t('SignIn')}` }}
  </q-btn>

  <q-modal v-model="modalVisible" :header="`${$t('ResetPwd')}`" :menuBtn="false" class="reset-pwd-modal" width="500">
    <ResetPwd v-model="modalVisible"></ResetPwd>
  </q-modal>

</template>

<script setup>
import { Cookies } from 'quasar'
import { userStores } from 'src/stores/user-stores'
import Base64 from 'src/utils/base64'
import { inject, ref } from 'vue'
import { useRouter } from 'vue-router'
import ResetPwd from './ResetPwd.vue'

const TENANT_ID = inject('TENANT_ID')

const isPwd = ref(true)
const loginForm = ref({})
const loading = ref(false)
const rememberMe = ref(false)
const modalVisible = ref(false)

const router = useRouter()
const keyCode = ref(0)
const tenInput = ref(null)
const pwdInput = ref(null)
const nameInput = ref(null)

const togglePWD = () => {
  isPwd.value = !isPwd.value
}

const getCookie = () => {
  const loginName = Cookies.get('loginName') || ''
  const password = Base64.decode(Cookies.get('password') || '')
  rememberMe.value = Boolean(Cookies.get('rememberMe'))
  loginForm.value = { loginName, password, tenantId: TENANT_ID, loginType: 'NAME_PASSWORD' }
}

getCookie()

const setCookie = () => {
  if (rememberMe.value) {
    Cookies.set('loginName', loginForm.value.loginName, { expires: 30 })
    Cookies.set('password', Base64.encode(loginForm.value.password), { expires: 30 })
    Cookies.set('rememberMe', String(rememberMe.value), { expires: 30 })
  } else {
    Cookies.remove('loginName')
    Cookies.remove('password')
    Cookies.remove('rememberMe')
  }
}

const setKeyCode = e => (keyCode.value = e.keyCode)

const login = keyType => {
  if (keyCode.value === 229 && typeof keyType === 'string') return // 中文输入法输入中文情况下 keydown.enter事件键值为229
  if (keyType === 'Input' && !nameInput.value.validate()) return nameInput.value.focus()
  if (keyType === 'PWD' && !pwdInput.value.validate()) return pwdInput.value.focus()
  if (!nameInput.value.validate()) return nameInput.value.focus()
  if (!pwdInput.value.validate()) return pwdInput.value.focus()

  pwdInput.value.blur()
  nameInput.value.blur()

  setCookie()
  loading.value = true
  loginForm.value.getOSS = true
  userStores().LoginByName(loginForm.value).then(async ({ done }) => {
    await router.replace('/dashboard/console')
    done && done()
    loading.value = !loading.value
  }).catch(() => {
    loading.value = !loading.value
  })
}
</script>